package com.ycwl.freetv.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbAccessory;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Build;
import android.os.Environment;
import android.os.UserManager;
import android.os.storage.StorageManager;
import android.os.storage.StorageVolume;
import android.provider.Settings;
import android.util.Log;

import com.ycwl.freetv.BaseActivity;

import java.util.List;

public class UsbReceiver extends BroadcastReceiver {
    static String TAG = "UsbReceiver";
    private boolean isRegister = false;

    private static int reCount = 0;
    BaseActivity baseActivity = null;
    public UsbReceiver(BaseActivity activity) {
        baseActivity = activity;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        // 设备挂载成功，可以开始读取数据
        if (((reCount & 0x1) == 0) && intent != null && intent.getAction() == Intent.ACTION_MEDIA_MOUNTED) {
            Log.d(TAG,"path======:"+ intent.getData().getPath() + "======:" +intent.getAction());
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
//                Log.w(TAG, "check permission ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION");
//                if (!Environment.isExternalStorageManager()) {
//                    Log.w(TAG, "has no permission ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION");
//                    Intent intent1 = new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
//                    context.startActivity(intent1 );
//                }
//            }
            baseActivity.OnUsbMount(intent.getData().getPath());
        }
        reCount++;
    }
    public void register(Context context) {
        if (isRegister) return;
        IntentFilter filter = new IntentFilter();
        filter.addDataScheme("file");
        filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
        context.registerReceiver(this, filter);
        isRegister = true;
    }
    public void unRegister(Context context) {
        if (!isRegister) return;
        isRegister = false;
        context.unregisterReceiver(this);
    }
}
